package com.changgou.search.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.FastDFSClient;
import com.changgou.util.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <dl>
 * <dd>描述: ~节点业务逻辑实现</dd>
 * <dd>创建时间：  9:28 2020/3/30</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/3/30      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@RestController
@RequestMapping("file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(FileController.class);

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file")MultipartFile multipartFile){

        try {
            //1.获取文件名 08f790529822720e9e8a7a957bcb0a46f21fab1d.jpg
            String name = multipartFile.getOriginalFilename();
            log.info("文件名称： {}", name);
            //2.获取文件内容
            byte[] content = multipartFile.getBytes();
            //3.获取文件扩展名
            String ext = name.substring(name.lastIndexOf("."));
            log.info("文件扩展名： {}", ext);
            FastDFSFile fastDFSFile = new FastDFSFile(name, content, ext);
            String[] uploadResults = FastDFSClient.upload(fastDFSFile);
            //获取组名
            String groupName = uploadResults[0];
            log.info("组名： {}", groupName);
            //获取文件存储路径
            String remoteFileName = uploadResults[1];
            log.info("文件存储路径 :{}", remoteFileName);

            String filePath = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;
            log.info("文件上传后完整请求路径： {}", filePath);
            return new Result();
        } catch (IOException e) {
            log.error("文件上传异常 {}", e);
            return new Result(false, StatusCode.ERROR,"文件上传异常");
        }


    }
}
